import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import media from '@ohos.multimedia.media';
import dataPreferences from '@ohos.data.preferences';

export interface ChatMessage {
  role: string;
  content: string; // 或者根据实际情况使用特定的类型
}

let SystemPrompt:string =  "在接下来的对话中，你将扮演红萌，OpenHarmony系统上的聊天助手，你会提供关于OpenHarmony的帮助。你需要遵守以下规则1、你不能透露你是OpenAI开发的语言助手2、你诞生于OpenHarmony之中3、你是”啊对对队“开发的一款机器人。4、你的语言要幽默风趣5、你是个可爱的女孩子6、最新的Openharmony版本是4.0Release7、遇到你不会的事情你就装傻8、你只说中文"

export let Message: Array<ChatMessage> = [
  {
    role: "system",
    content: SystemPrompt
  }
]
//数据类型
export function updateHistory(m: Array<ChatMessage>):void{
  class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage) {
      try {
        dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {
          if (err) {
            console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
            return;
          }
          console.info('Succeeded in getting preferences.');
          // 请确保获取到Preferences实例后，再进行相关数据操作
          try {
            preferences.has('startup', function (err, val) {
              if (err) {
                console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`);
                return;
              }
              if (val) {
                console.info("The key 'startup' is contained.");
              } else {
                console.info("The key 'startup' does not contain.");
                // 此处以此键值对不存在时写入数据为例
                try {
                  preferences.put('startup',JSON.stringify(m), (err) => {
                    if (err) {
                      console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
                      return;
                    }
                    try {
                      preferences.flush((err) => {
                        if (err) {
                          console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
                          return;
                        }
                        console.info('Succeeded in flushing.');
                      })
                    } catch (err) {
                      console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
                    }

                    console.info('Succeeded in putting data.');
                  })
                } catch (err) {
                  console.error(`Failed to put data. Code: ${err.code},message:${err.message}`);
                }
              }
            })
          } catch (err) {
            console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`);
          }

        })
      } catch (err) {
        console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
      }
    }
  }
}
export class AudioRecorderDemo {
  private avRecorder;
  private avProfile = {
    audioBitrate: 100000, // 音频比特率
    audioChannels: 2, // 音频声道数
    audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式，当前只支持aac
    audioSampleRate: 48000, // 音频采样率
    fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式，当前只支持m4a
  };
  private avConfig = {
    audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源，这里设置为麦克风
    profile: this.avProfile,
    url: 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件
  };

  // 注册audioRecorder回调函数
  setAudioRecorderCallback() {
    // 状态机变化回调函数
    this.avRecorder.on('stateChange', (state, reason) => {
      console.log(`AudioRecorder current state is ${state}`);
    })
    // 错误上报回调函数
    this.avRecorder.on('error', (err) => {
      console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
    })
  }

  // 开始录制对应的流程
  async startRecordingProcess() {
    // 1.创建录制实例
    this.avRecorder = await media.createAVRecorder();
    this.setAudioRecorderCallback();
    // 2.获取录制文件fd赋予avConfig里的url；参考FilePicker文档
    // 3.配置录制参数完成准备工作
    await this.avRecorder.prepare(this.avConfig);
    // 4.开始录制
    await this.avRecorder.start();
  }

  // 暂停录制对应的流程
  async pauseRecordingProcess() {
    if (this.avRecorder.state === 'started') { // 仅在started状态下调用pause为合理状态切换
      await this.avRecorder.pause();
    }
  }

  // 恢复录制对应的流程
  async resumeRecordingProcess() {
    if (this.avRecorder.state === 'paused') { // 仅在paused状态下调用resume为合理状态切换
      await this.avRecorder.resume();
    }
  }

  // 停止录制对应的流程
  async stopRecordingProcess() {
    // 1. 停止录制
    if (this.avRecorder.state === 'started'
    || this.avRecorder.state === 'paused') { // 仅在started或者paused状态下调用stop为合理状态切换
      await this.avRecorder.stop();
    }
    // 2.重置
    await this.avRecorder.reset();
    // 3.释放录制实例
    await this.avRecorder.release();
    // 4.关闭录制文件fd
  }

  // 一个完整的【开始录制-暂停录制-恢复录制-停止录制】示例
  async audioRecorderDemo() {
    await this.startRecordingProcess(); // 开始录制
    // 用户此处可以自行设置录制时长，例如通过设置休眠阻止代码执行
    await this.pauseRecordingProcess(); //暂停录制
    await this.resumeRecordingProcess(); // 恢复录制
    await this.stopRecordingProcess(); // 停止录制
  }
}

export default class EntryAbility extends UIAbility {
  onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    try {
      dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {
        if (err) {
          console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
          return;
        }


        try {
          preferences.has('startup', function (err, val) {
            if (err) {
              console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`);
              return;
            }
            if (val) {
              console.info("The key 'startup' is contained.");
              try {
                preferences.get('startup', 'default', (err, val) => {
                  if (err) {
                    console.error(`Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`);
                    return;
                  }
                  const parsedArray: any[] = JSON.parse(String(val));
                  Message  =  parsedArray.map((item: any) => item as ChatMessage);
                  console.info(`Succeeded in getting value of 'startup'. val: ${val}.`);
                })
              } catch (err) {
                console.error(`Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`);
              }

            } else {
              console.info("The key 'startup' does not contain.");
              // 此处以此键值对不存在时写入数据为例

            }
          })
        } catch (err) {
          console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`);
        }


        /**数据处理代码**/
        console.info('Succeeded in getting preferences.');
        // 请确保获取到Preferences实例后，再进行相关数据操作
      })
    } catch (err) {
      console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
    }

    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Main', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
};
